import itsdangerous
from flask import Flask, redirect, request, session, Response, jsonify, current_app
from flask_mail import Mail
from flask_httpauth import HTTPTokenAuth
from myapp.models.base import db
from myapp.models.result import Result

mail = Mail()
auth = HTTPTokenAuth(scheme='Bearer')


def create_app():
    app = Flask(__name__)
    app.config.from_object('myapp.secure')
    app.config.from_object('myapp.setting')
    # 邮件注册
    mail.init_app(app)
    # 注册蓝图
    register_blueprint(app)
    # 注册SQLAlchemy
    db.init_app(app)
    with app.app_context():
        from . import models
        db.create_all()
    app.response_class = AutoJsonifyResponse
    return app


def register_blueprint(app):
    # 注册book里web的蓝图
    from myapp.controller import api
    app.register_blueprint(api)


@auth.verify_token
def verify_token(token):
    salt = current_app.config['SECRET_KEY']
    expiration = current_app.config['EXPIRATION']
    t = itsdangerous.TimedJSONWebSignatureSerializer(salt, expires_in=expiration)  # 过期时间600秒
    try:
        user_detail = t.loads(token.encode('utf-8'))
    except Exception as e:
        return None
    if user_detail.get('status') != -1:
        return user_detail
    return None


@auth.error_handler
def unauthorized():
    return Result.fail("unauthorized")


class AutoJsonifyResponse(Response):
    @classmethod
    def force_type(cls, response, environ=None):
        if isinstance(response, (list, dict)):
            response = jsonify(response)
        return super(Response, cls).force_type(response, environ)

